package com.lc.controller;

import com.lc.mapper.UserMapper;
import com.lc.pojo.User;
import com.lc.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;



    @RequestMapping("/delete/{user_phone}")
    public String deleteUser(@PathVariable String user_phone) throws Exception {
        int succ = userMapper.deleteUserByPhone(user_phone);
        if (succ == 1) {
            String successMsg = URLEncoder.encode("删除成功", "UTF-8");
            return "redirect:/user?successMsg=" + successMsg;
        } else {
            String errorMsg = URLEncoder.encode("删除失败", "UTF-8");
            return "redirect:/user?successMsg=" + errorMsg;
        }
    }
    @RequestMapping("/update")
    public String updateUser(HttpServletRequest request, User user) throws Exception {
        User userNew = new User();
        BeanUtils.copyProperties(user, userNew);
        Boolean succ = userService.updateUser(userNew);
        if (succ) {
            String successMsg = URLEncoder.encode("修改成功", "UTF-8");
            return "redirect:/user?successMsg=" + successMsg;
        } else {
            String errorMsg = URLEncoder.encode("修改失败", "UTF-8");
            return "redirect:/user?successMsg=" + errorMsg;
        }
    }

    @RequestMapping("/toEdit/{user_phone}")
    public String toAdd(@PathVariable String user_phone, Model model) throws Exception {
        // 通过ID查询舰船并返回前台
        User user = userMapper.queryUserByName(user_phone);
        model.addAttribute("user", user);
        return "mange/editUser";

    }

    @RequestMapping("/toAdd")
    public String toAdd() throws Exception {
        return "mange/addUser";

    }



    @RequestMapping("/user")
    public String userList(Model model){
        List<User> users = userMapper.queryUserList();
        model.addAttribute("users", users);
        return "mange/user";
    }
}
